package com.example.ItPhotoAlbumCloud.model;

import com.example.ItPhotoAlbumCloud.utils.Pagination;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;

/**
 * 分页DB模型
 * 小仙 创建人 2023-03-12 08:54:11.
 */
public class PaginationDO extends Pagination implements Serializable{

    /** 分页起始点 */
    private Integer offset;

    /** 分页大小 */
    private Integer rows;

    /**
     * 重写 setPageIndex() ，在实例设置了 pageIndex和pageSize后，自动设置offset和rows
     * @param pageIndex
     */
    @Override
    public void setPageIndex(Integer pageIndex) {
        super.setPageIndex(pageIndex);
        if (this.getPageSize() != null){
            this.rows = this.getPageSize();
            this.offset = getLimitOffset(this.getPageIndex(), this.getPageSize());
        }
    }

    /**
     * 重写 setPageSize() ，在实例设置了 pageIndex和pageSize后，自动设置offset和rows
     * @param pageSize
     */
    @Override
    public void setPageSize(Integer pageSize) {
        super.setPageSize(pageSize);
        if (this.getPageIndex() != null){
            this.rows = pageSize;
            this.offset = getLimitOffset(this.getPageIndex(), this.getPageSize());
        }
    }

    public Integer getOffset() {
        return offset;
    }

    public void setOffset(Integer offset) {
        this.offset = offset;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }


    /**
     * 向 request 填充 offset 与 rows 后返回 PaginationDO
     * @param request
     * @return
     */
    public static PaginationDO setRequestOffsetAndRows(JSONObject request){
        if (null == request){
            return null;
        }

        Integer pageIndex = request.getInteger("pageIndex");
        Integer pageSize = request.getInteger("pageSize");
        if (null == pageIndex || null == pageSize){
            return null;
        }

        // 解析成PaginationDO
        PaginationDO paginationDO = JSON.toJavaObject(request, PaginationDO.class);

        // 向 request 填充 offset 与 rows
        request.put("offset", paginationDO.getOffset());
        request.put("rows", paginationDO.getRows());
        return paginationDO;
    }


    /**
     * 计算分页起始索引
     * @param page 指定分页
     * @param pageSize 分页大小
     * @return
     */
    public static int getLimitOffset(int page, int pageSize){
        // 兼容等于0的情况
        page = page <= 0 ? 1 : page;
        return (page - 1) * pageSize;
    }
}

